package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
public class LoginController {

    @Reference
    private LoginService loginService;

    @Autowired
    private JedisPool jedisPool;

    //   /login/check
    @RequestMapping("/login/check")
    public Result check(String telephone , String validateCode, HttpServletResponse resp, HttpServletRequest req){

        //  validateCode  验证码的 key
        //  telephone  手机号的key

        // 1 校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
        try {
            String validateCodeInJedisPool = jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);
//            System.out.println("validateCodeInJedisPool="+validateCodeInJedisPool);
//            System.out.println("validateCode="+validateCode);
            if(validateCodeInJedisPool == null || validateCode == null || !validateCode.equals(validateCodeInJedisPool)){
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
            // 则判断当前用户是否为会员，如果不是会员则自动完成会员注册
            //查询会员表  看是否为空
            Member member = loginService.getByPhoneNumber(telephone);
            if(member == null){
                loginService.insertMember(telephone);
            }
            //member = new Member();
            member.setPhoneNumber(telephone);

            //3、向客户端写入Cookie，内容为用户手机号
            //向客户端浏览器写入Cookie，内容为手机号  telephone
            Cookie cookie = new Cookie("login_member_telephone", MD5Utils.md5(telephone));
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            resp.addCookie(cookie);

            //	4、将 会员信息保存到 Redis ，使用手机号作为key ， 保存时长为30分钟
            //将会员信息保存到Redis
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(MD5Utils.md5(telephone),60*30,json);

            return new Result(true,MessageConstant.LOGIN_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"登陆失败");
        }
    }

}


